package com.hmily.dubbo.provider.impl.async;

import com.hmily.dubbo.api.async.AsyncUserQueryFacade;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.RpcContext;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * <h1>异步用户信息查询接口实现类。</h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2021-10-19
 *
 */
public class AsyncUserQueryFacadeImpl implements AsyncUserQueryFacade {

    private ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(4, 4, 0L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());


    @Override
    public String queryUserById(String id) {
        String resultMsg = "async, id = " + id + ", my name is yuki.";

        AsyncContext asyncContext = RpcContext.startAsync();
        // 一旦需要走异步操作，那么一定会和线程池联系起来
        poolExecutor.execute(() -> {
            asyncContext.signalContextSwitch();

            // 这里模拟执行一段耗时的业务逻辑
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(resultMsg);
            asyncContext.write(resultMsg);
        });

        return null;
    }

    @Override
    public CompletableFuture<String> queryUserByName(String name) {
        return CompletableFuture.supplyAsync(() -> {
            // 这里模拟执行一段耗时的业务逻辑
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String resultMsg = "async, name = " + name + ", my name is hmily.";
            System.out.println(resultMsg);
            return resultMsg;
        });
    }
}
